/**
 * 
 */
package info.niwota.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import jvs.peer.util.Log;
import x.org.apache.http.Header;
import x.org.apache.http.HttpEntity;
import x.org.apache.http.HttpEntityEnclosingRequest;
import x.org.apache.http.HttpException;
import x.org.apache.http.HttpRequest;
import x.org.apache.http.HttpResponse;
import x.org.apache.http.NameValuePair;
import x.org.apache.http.ParseException;
import x.org.apache.http.protocol.HttpContext;
import x.org.apache.http.protocol.HttpRequestHandler;
import x.org.apache.http.util.EntityUtils;

/**
 * @author qiangli
 * 
 */
public class ServletAdapterHandler implements HttpRequestHandler {
	//https://issues.apache.org/bugzilla/show_bug.cgi?id=40160
	private static final String MS_WEBDAV_AGENT = "Microsoft Data Access Internet Publishing Provider Protocol Discovery";

	private static final String URL_ENCTYPE = "application/x-www-form-urlencoded";

	private static final String TAG = "ServletAdapterHandler";

	private Map<String, String> parseParams(HttpRequest request)
			throws ParseException, IOException {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		final String charset = "UTF-8";

		final String requestUri = request.getRequestLine().getUri();
		Utils.parseUri(params, requestUri, charset);
		if (request instanceof HttpEntityEnclosingRequest) {
			HttpEntity entity = ((HttpEntityEnclosingRequest) request)
					.getEntity();

			if (entity != null) {
				Header th = entity.getContentType();
				if (th == null || URL_ENCTYPE.equals(th.getValue())) {
					Header eh = entity.getContentEncoding();
					String encoding = charset;
					if (eh != null) {
						encoding = eh.getValue();
					}
					String c = EntityUtils.toString(entity);
					Utils.parseContent(params, c, encoding);
					EntityUtils.consume(entity);
				}
			}
		}
		HashMap<String, String> map = new HashMap<String, String>();
		for (NameValuePair p : params) {
			map.put(p.getName(), p.getValue());
		}
		return map;
	}

	
	public void handle(HttpRequest request, HttpResponse response,
			HttpContext context) throws HttpException, IOException {
		Map<String, String> params = parseParams(request);
		context.setAttribute(HttpServletRequestWrapper.PARAMETERS_KEY, params);

		if (Log.DEBUG) {
			Log.d(TAG, request.getRequestLine() + " params: " + params);
		}

		HttpServletRequestWrapper req = new HttpServletRequestWrapper(request,
				context);
		HttpServletResponseWrapper res = new HttpServletResponseWrapper(
				response, context);

		//
		HttpServlet serv = getServlet();

		if (serv != null) {
			try {

				if (Log.TRACE) {
					print(">>>", request.getAllHeaders());
				}

				serv.service(req, res);

				if (Log.TRACE) {
					print("<<<", response.getAllHeaders());
				}
			} catch (ServletException e) {
				throw new HttpException(e.getMessage());
			}
		}
	}

	private void print(String tag, Header[] allHeaders) {
		for (int i = 0; i < allHeaders.length; i++) {
			Header h = allHeaders[i];
			Log.d(tag, h.getName() + ": " + h.getValue());
		}
	}

	protected HttpServlet getServlet() {
		return null;
	}

	protected ServletConfig servletConfig = new ServletConfig() {

		
		public String getServletName() {
			return this.getClass().getName();
		}

		
		public ServletContext getServletContext() {
			return servletContext;
		}

		
		public String getInitParameter(String name) {
			return null;
		}

		
		public Enumeration getInitParameterNames() {
			return null;
		}

	};

	protected ServletContext servletContext = new ServletContext() {

		
		public ServletContext getContext(String uripath) {
			// TODO Auto-generated method stub
			return null;
		}

		
		public String getContextPath() {
			// TODO Auto-generated method stub
			return null;
		}

		
		public int getMajorVersion() {
			// TODO Auto-generated method stub
			return 0;
		}

		
		public int getMinorVersion() {
			// TODO Auto-generated method stub
			return 0;
		}

		
		public String getMimeType(String file) {
			return null;
		}

		
		public Set getResourcePaths(String path) {
			// TODO Auto-generated method stub
			return null;
		}

		
		public URL getResource(String path) throws MalformedURLException {
			// TODO Auto-generated method stub
			return null;
		}

		
		public InputStream getResourceAsStream(String path) {
			// TODO Auto-generated method stub
			return null;
		}

		
		public RequestDispatcher getRequestDispatcher(String path) {
			// TODO Auto-generated method stub
			return null;
		}

		
		public RequestDispatcher getNamedDispatcher(String name) {
			// TODO Auto-generated method stub
			return null;
		}

		
		public Servlet getServlet(String name) throws ServletException {
			// TODO Auto-generated method stub
			return null;
		}

		
		public Enumeration getServlets() {
			// TODO Auto-generated method stub
			return null;
		}

		
		public Enumeration getServletNames() {
			// TODO Auto-generated method stub
			return null;
		}

		
		public void log(String msg) {
			// TODO Auto-generated method stub

		}

		
		public void log(Exception exception, String msg) {
			// TODO Auto-generated method stub

		}

		
		public void log(String message, Throwable throwable) {
			// TODO Auto-generated method stub

		}

		
		public String getRealPath(String path) {
			// TODO Auto-generated method stub
			return null;
		}

		
		public String getServerInfo() {
			// TODO Auto-generated method stub
			return null;
		}

		
		public String getInitParameter(String name) {
			// TODO Auto-generated method stub
			return null;
		}

		
		public Enumeration getInitParameterNames() {
			// TODO Auto-generated method stub
			return null;
		}

		
		public Object getAttribute(String name) {
			// TODO Auto-generated method stub
			return null;
		}

		
		public Enumeration getAttributeNames() {
			// TODO Auto-generated method stub
			return null;
		}

		
		public void setAttribute(String name, Object object) {
			// TODO Auto-generated method stub

		}

		
		public void removeAttribute(String name) {
			// TODO Auto-generated method stub

		}

		
		public String getServletContextName() {
			// TODO Auto-generated method stub
			return null;
		}

	};
}
